<?php

namespace Lambq\Websocket;

use Lambq\Websocket\Parser;
use Lambq\Websocket\Rooms\RoomContract;
use Lambq\Websocket\WebSocket;
use Illuminate\Support\ServiceProvider;
use Illuminate\Container\Container;

class WebsocketServiceProvider extends ServiceProvider
{
    protected $commands = [
        Console\InstallCommand::class,
    ];

    public function boot()
    {
        $this->publishFiles();
        $this->mergeConfigs();
    }

    protected function publishFiles()
    {
        $this->publishes([__DIR__. '/config/websocket.php' => config_path('websocket.php'), 'lambq-websocket-config']);
    }

    protected function mergeConfigs()
    {
        $this->mergeConfigFrom(__DIR__ . '/config/websocket.php', 'websocket');
    }

    public function register()
    {
        // WorkerStart 事件发生时 Laravel 已经初始化完成，在这里做一些组件绑定到容器的初始化工作最合适
        $this->app->singleton(Parser::class, function () {
            $parserClass = config('laravels.websocket.parser');
            return new $parserClass;
        });
        $this->app->alias(Parser::class, 'swoole.parser');

        $this->app->singleton(RoomContract::class, function () {
            $driver         = config('laravels.websocket.drivers.default', 'table');
            $driverClass    = config('laravels.websocket.drivers.' . $driver);
            $driverConfig   = config('laravels.websocket.drivers.settings.' . $driver);
            $roomInstance   = new $driverClass($driverConfig);
            if ($roomInstance instanceof RoomContract) {
                $roomInstance->prepare();
            }
            return $roomInstance;
        });

        $this->app->alias(RoomContract::class, 'swoole.room');

        $this->app->singleton(WebSocket::class, function (Container $app) {
            return new WebSocket($app->make(RoomContract::class));
        });

        $this->app->alias(WebSocket::class, 'swoole.websocket');

        $this->commands($this->commands);
    }

    /**
     * @return array
     */
    public function provides()
    {
        return array('websocket');
    }
}